using System;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Wicresoft.SelfService.DAO;
using Wicresoft.SelfService.BL;
using Wicresoft.SelfService.BL.Interface;
using Wicresoft.SelfService.DAL;
using Wicresoft.SelfService.Portal.Service;
using Wicresoft.SelfService.Portal.Models;
namespace Wicresoft.SelfService.Portal.Controllers
{
    public class ITServiceController : BaseController
    {
        private string ARServer;
        private string Mid_Base;
        private string appSystemName;
        public ITServiceHelper helper { get; private set; }
        public Wicresoft.SelfService.BL.Interface.IBreakDown IBreakDown { get; private set; }
        public IUserSync userSync { get; private set; }
        public Wicresoft.SelfService.BL.Interface.IAppSystem myAppSystem { get; private set; }
        public static WFService.ApproveFlowClient IApproveFlow { get; private set; }
        protected override void Initialize(RequestContext requestContext)
        {
            if (helper == null) { helper = new ITServiceHelper(); }
            if (IBreakDown == null) { IBreakDown = new Wicresoft.SelfService.BL.BreakDown(); }
            if (userSync == null) { userSync = new UserSync(); }
            if (myAppSystem == null) { myAppSystem = new MyAppSystem(); }
            if (IApproveFlow == null) { IApproveFlow = new WFService.ApproveFlowClient(); }

            ARServer = ConfigurationManager.AppSettings["ARServer"];
            Mid_Base = ConfigurationManager.AppSettings["ITSM_Mid_Tier"];//without end "/"
            appSystemName = ConfigurationManager.AppSettings["ApplicationSystemName"];
            if (string.IsNullOrEmpty(appSystemName)) appSystemName = "应用系统";
            base.Initialize(requestContext);
        }
        #region create IT service requests, any signed-in user can create an IT service request
        [Authorize]
        public ActionResult Create(string ServiceType)
        {
            ServiceDetail model = new ServiceDetail();
            DateTime dt = DateTime.UtcNow;
            model.serviceRequestID = createCodeNumber();
            model.account = userSync.getUserInfo(System.Web.HttpContext.Current.User.Identity.Name);
            model.serviceType = helper.getServiceList_By_PartialName(ServiceType.ToLower().Trim());
            model.serviceTypeID = model.serviceType.serviceTypeID;
            model.actions = new List<actionType>();
            model.actions.Add(actionType.uploadFile);
            this.generateSelectListDataModel(model);

            //查询知识库按钮的基准url
            ViewBag.SearchBaseUrl = string.Format("{0}/arsys/forms/{1}/RKM%3ASearchDialog/Default+Admin+View/?format=html&F302258625=", Mid_Base, ARServer);

            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Create(ServiceDetail model, string action)
        {
            model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
            action = action.Trim().ToUpper();
            switch (action)
            {
                case "提交":
                case "CREATE":
                    Wicresoft.SelfService.WFInterface.RequestParam requestParam = new Wicresoft.SelfService.WFInterface.RequestParam
                    {
                        ApplicationId = model.serviceRequestID,
                        NeedApprove = Convert.ToBoolean(model.serviceType.needApprove),
                        RequestCode = null,
                        SecurityCode = "fjyc.wicresoft"
                    };
                    Wicresoft.SelfService.WFInterface.RequestResult requestResult = IApproveFlow.Create(requestParam);
                    model.flowInstanceId = requestResult.FlowInstanceId.ToString();
                    model.stepID = (int)(serviceStep)Enum.Parse(typeof(serviceStep), requestResult.Step, true);
                    model.stauts = (int)(serviceStatus)Enum.Parse(typeof(serviceStatus), requestResult.Status, true);
                    
                    #region //创建通知短信
                    MsgHelper wsMsg = new MsgHelper();
                    UserAndRoleInfo GetAssigners = new UserAndRoleInfo();
                    if (requestParam.NeedApprove && model.account.company == "宁德市烟草专卖局")
                    {

                        var assigners = GetAssigners.GetUserRoleRelationshipByRoleID(1);   //model.stepID

                        string description = model.description;
                        if (description.Length > 20)
                            description = description.Substring(0, 20);
                        string dsc = "自服务单提醒:" + model.serviceRequestID + ",提交人：" + model.account.userName + ",摘要:" + description;

                        if (assigners.Count > 0)
                        {
                            foreach (var item in assigners)
                            {
                                WS_Message wsmodel = new WS_Message()
                                {
                                    cChr_LoginID = item.AccountID,
                                    cInt_Status = 0,
                                    //AssignedTo = item.AccountID,
                                    cChr_PhoneNumber = item.Phone,
                                    cChr_Message = dsc,
                                    cChr_Others3 = model.account.company,
                                    Submitter = model.account.accountID,
                                    Short_Description=dsc
                                };
                                //bool retmsg = wsMsg.Create(wsmodel);
                                wsMsg.CreateMessage(wsmodel);
                            }
                        }
                    }
                    #endregion

                    break;
                case "保存":
                    model.stauts = 0;
                    break;
                default:
                    model = null;
                    return View(model);
            }
            model.accountID = model.account.accountID;
            model.companyIDs = model.account.company;
            int bdLvl1, bdLvl2, bdLvl3;
            if (int.TryParse(model.breakDownlvl1, out bdLvl1))
            {
                BreakDownList bd1 = IBreakDown.GetBreakDownInfo(bdLvl1);
                if (bd1 != null) model.breakDownlvl1 = bd1.LvlName;
            }
            if (int.TryParse(model.breakDownlvl2, out bdLvl2))
            {
                if (model.breakDownlvl1.Trim() == appSystemName.Trim())
                {
                    BusinessSystem bs2 = myAppSystem.getAppSystem_By_ID(bdLvl2);
                    if (bs2 != null)
                        model.breakDownlvl2 = bs2.Name;
                    else
                        model.breakDownlvl2 = null;
                }
                else
                {
                    BreakDownList bd2 = IBreakDown.GetBreakDownInfo(bdLvl2);
                    if (bd2 != null)
                        model.breakDownlvl2 = bd2.LvlName;
                    else
                        model.breakDownlvl2 = null;
                }
            }
            if (int.TryParse(model.breakDownlvl3, out bdLvl3))
            {
                BreakDownList bd3 = IBreakDown.GetBreakDownInfo(bdLvl3);
                if (bd3 != null)
                    model.breakDownlvl3 = bd3.LvlName;
                else
                    model.breakDownlvl3 = null;
            }
            bool result = helper.CreateNewITService(model);
            if (result)
            {
                if (model.stauts == (int)serviceStatus.Waiting && model.stepID == (int)serviceStep.event_process)
                {
                    //生成事件代码...（可以考虑使用异步，以减少页面的阻塞时间）
                    try
                    {
                        ITSMAccidentDAL eventHandler = new ITSMAccidentDAL();
                        string incidentId = eventHandler.createAccident(model);
                        helper.UpdateServiceRecords(model.serviceRequestID, null, null, incidentId);
                    }
                    catch (Exception e)
                    {
                        helper.rollbackTransaction();
                        helper.closeDBConnection();
                        this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                        throw (e);
                    }
                }
                helper.commitTransaction();
                helper.closeDBConnection();
                if (model.stauts == (int)serviceStatus.Draft)//保存后跳转到草稿
                    return RedirectToAction("MyDraft", "WorkList");
                return RedirectToAction("Index");
            }
            else
            {
                helper.rollbackTransaction();
                helper.closeDBConnection();
                this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                Response.Write("<script>alert('操作失败，请稍后再试！')</script>");
                model.actions = new List<actionType>();
                model.actions.Add(actionType.uploadFile);
                model.attachments = helper.getAttachments_By_ServiceRequestID(model.serviceRequestID);
                this.generateSelectListDataModel(model);
                return View(model);
            }
        }
        #endregion
        #region update IT service requests, only the owner has the permission
        [Authorize]
        public ActionResult Update(string serviceRequestID)
        {
            ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
            if (model != null)
            {
                UserInfo ui_submitter = this.userSync.getUserInfo(model.accountID);
                if (System.Web.HttpContext.Current.User.Identity.Name == ui_submitter.accountID && (model.stauts == 0 || model.stauts == 5))
                {
                    model.actions = new List<actionType>();
                    model.actions.Add(actionType.uploadFile);
                    if (model.stauts == 5)
                    {
                        model.actions.Add(actionType.undo);
                        model.actions.Add(actionType.checkSuggestion);
                    }
                    model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
                    model.serviceTypeID = model.serviceType.serviceTypeID;
                    model.attachments = helper.getAttachments_By_ServiceRequestID(model.serviceRequestID.Trim().ToLower());
                    model.account = ui_submitter;
                    this.generateSelectListDataModel(model);
                }
                else
                {
                    model = null;
                }
            }

            //查询知识库按钮的基准url
            ViewBag.SearchBaseUrl = string.Format("{0}/arsys/forms/{1}/RKM%3ASearchDialog/Default+Admin+View/?format=html&F302258625=", Mid_Base, ARServer);

            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Update(ServiceDetail model, string action)
        {
            ServiceDetail modelActual = helper.getServiceRequest_By_ID(model.serviceRequestID.Trim().ToLower());
            if (modelActual.accountID == System.Web.HttpContext.Current.User.Identity.Name && (modelActual.stauts == 0 || modelActual.stauts == 5))
            {
                model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
                action = action.Trim().ToUpper();
                switch (action)
                {
                    case "提交":
                    case "UPDATE":
                        Wicresoft.SelfService.WFInterface.RequestParam requestParam = new Wicresoft.SelfService.WFInterface.RequestParam
                        {
                            ApplicationId = model.serviceRequestID,
                            NeedApprove = Convert.ToBoolean(model.serviceType.needApprove),
                            RequestCode = Guid.NewGuid().ToString(),
                            SecurityCode = "fjyc.wicresoft"
                        };
                        Wicresoft.SelfService.WFInterface.RequestResult requestResult = IApproveFlow.Create(requestParam);
                        model.flowInstanceId = requestResult.FlowInstanceId.ToString();
                        model.stepID = (int)(serviceStep)Enum.Parse(typeof(serviceStep), requestResult.Step, true);
                        model.stauts = (int)(serviceStatus)Enum.Parse(typeof(serviceStatus), requestResult.Status, true);
                        model.updateTime = DateTime.Now;
                        break;
                    case "保存":
                        model.stauts = 0;
                        break;
                    default:
                        model = null;
                        return View(model);
                }
                model.accountID = model.account.accountID;
                model.companyIDs = model.account.company;
                int bdLvl1, bdLvl2, bdLvl3;
                if (int.TryParse(model.breakDownlvl1, out bdLvl1))
                {
                    BreakDownList bd1 = IBreakDown.GetBreakDownInfo(bdLvl1);
                    if (bd1 != null) model.breakDownlvl1 = bd1.LvlName;
                }
                if (int.TryParse(model.breakDownlvl2, out bdLvl2))
                {
                    if (model.breakDownlvl1.Trim() == appSystemName.Trim())
                    {
                        BusinessSystem bs2 = myAppSystem.getAppSystem_By_ID(bdLvl2);
                        if (bs2 != null) model.breakDownlvl2 = bs2.Name;
                    }
                    else
                    {
                        BreakDownList bd2 = IBreakDown.GetBreakDownInfo(bdLvl2);
                        if (bd2 != null) model.breakDownlvl2 = bd2.LvlName;
                    }
                }
                if (int.TryParse(model.breakDownlvl3, out bdLvl3))
                {
                    BreakDownList bd3 = IBreakDown.GetBreakDownInfo(bdLvl3);
                    if (bd3 != null) model.breakDownlvl3 = bd3.LvlName;
                }
                bool result = helper.UpdateITService(model);
                if (result)
                {
                    if (model.stauts == (int)serviceStatus.Waiting && model.stepID == (int)serviceStep.event_process)
                    {
                        try
                        {
                            //生成事件代码...（可以考虑使用异步，以减少页面的阻塞时间）
                            ITSMAccidentDAL eventHandler = new ITSMAccidentDAL();
                            string incidentId = eventHandler.createAccident(model);
                            helper.UpdateServiceRecords(model.serviceRequestID, null, null, incidentId);

                        }
                        catch (Exception e)
                        {
                            helper.rollbackTransaction();
                            helper.closeDBConnection();
                            this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                            throw (e);
                        }
                    }

                    helper.commitTransaction();
                    helper.closeDBConnection();
                    return RedirectToAction("Index");
                }
                else
                {
                    helper.rollbackTransaction();
                    helper.closeDBConnection();
                    this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                    Response.Write("<script>alert('操作失败，请稍后再试！')</script>");
                    model.account = helper.getUserInfo_By_AccountID(model.accountID);
                    model.actions = new List<actionType>();
                    model.actions.Add(actionType.uploadFile);
                    model.attachments = helper.getAttachments_By_ServiceRequestID(model.serviceRequestID);
                    this.generateSelectListDataModel(model);
                    return View(model);
                }
            }
            else
            {
                return RedirectToAction("Error");
            }
        }
        #endregion
        #region view and take actions on IT service requests
        [Authorize]
        public ActionResult Views(string serviceRequestID)
        {
            ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
            if (model != null)
            {
                roleType role = this.getRoleType(model);
                serviceStatus status = (serviceStatus)model.stauts;
                serviceStep step = (serviceStep)model.stepID;
                model.actions = Common.getActions(role, status, step);
                model.account = userSync.getUserInfo(model.accountID);

                if (model.account != null)
                {
                    BusinessSystem bs = myAppSystem.getAppSystem_By_AppName(model.appName, model.account.company);
                    if (bs != null) model.appCategory = bs.category;
                }

                if (model.actions != null)
                {
                    if (model.breakDownlvl1 == "0") model.breakDownlvl1 = string.Empty;
                    if (model.breakDownlvl2 == "0") model.breakDownlvl2 = string.Empty;
                    if (model.breakDownlvl3 == "0") model.breakDownlvl3 = string.Empty;
                    model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
                    model.account = helper.getUserInfo_By_AccountID(model.accountID);
                    model.attachments = helper.getAttachments_By_ServiceRequestID(model.serviceRequestID.Trim().ToLower());
                    model.histories = helper.getServiceRecordHistory_By_serviceRequestID(model.serviceRequestID);
                    if (0 < model.stauts && model.stauts < 4)
                    {
                        string approveowner = model.approveOwner;
                        if (string.IsNullOrEmpty(approveowner))
                        {
                            ApproveSteps approveStep = helper.getApproveSteps_By_ID(model.stepID);
                            if (approveStep.stepName != "event_process")
                            {
                                model.CurrentProcessor = helper.getCurrentProcessor_By_RequestID(model.serviceRequestID);
                            }
                            else
                            {
                                model.CurrentProcessor = "ITSM服务台";
                            }
                        }
                        else
                        {
                            model.CurrentProcessor = approveowner;
                        }

                    }
                }
                else
                {
                    model = null;
                }
            }
            return View(model);
        }
        #endregion
        #region ajax calls
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public JsonResult undoServiceRequest(string serviceRequestID, string desc)
        {
            ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
            if (model.accountID != System.Web.HttpContext.Current.User.Identity.Name || model.stepID != 1) return null;

            string cStep = string.Empty;
            if (model.stepID.HasValue) cStep = Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString();
            Wicresoft.SelfService.WFInterface.ActionParam param = new Wicresoft.SelfService.WFInterface.ActionParam
            {
                FlowInstanceId = new Guid(model.flowInstanceId),
                CurrentStep = cStep,
                Action = "Cancel",
                RequestCode = Guid.NewGuid().ToString(),
                SecurityCode = "fjyc.wicresoft"
            };
            Wicresoft.SelfService.WFInterface.ActionResult actionResult = IApproveFlow.Update(param);
            if (string.IsNullOrEmpty(actionResult.ErrorMsg) || actionResult.ErrorMsg.Contains("Can't find the WorkflowApplication :"))
            {
                model.stauts = (int)serviceStatus.Canceled;
                bool undoStatus = helper.UpdateITServiceStatus(model.serviceRequestID.Trim().ToLower(), model.stauts);
                ServiceHistory history = new ServiceHistory();
                history.serviceRequestID = serviceRequestID;
                history.approverID = System.Web.HttpContext.Current.User.Identity.Name;
                UserInfo ui = helper.getUserInfo_By_AccountID(history.approverID);
                if (ui != null) history.approverName = ui.userName;
                history.action = "撤销";
                history.comments = desc;
                bool result2 = helper.CreateServiceRecordHistory(history);
                if (undoStatus && result2)
                {
                    helper.commitTransaction();
                    helper.closeDBConnection();
                    return Json(new { status = 1 });
                }
                else
                {
                    helper.rollbackTransaction();
                    helper.closeDBConnection();
                    this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                }
            }
            else
            {
                this.rollbackWF(model.flowInstanceId, actionResult.Step);
            }
            return Json(new { status = 0 });
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public JsonResult rejectServiceRequest(string serviceRequestID, string desc)
        {
            ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
            try
            {
                roleType role = this.getRoleType(model);
                serviceStatus status = (serviceStatus)model.stauts;
                serviceStep step = (serviceStep)model.stepID;
                model.actions = Common.getActions(role, status, step);
                if (model.actions.Contains(actionType.approve) == false) return Json(new { status = 0 });
                string cStep = string.Empty;
                if (model.stepID.HasValue) cStep = Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString();
                Wicresoft.SelfService.WFInterface.ActionParam param = new Wicresoft.SelfService.WFInterface.ActionParam
                {
                    FlowInstanceId = new Guid(model.flowInstanceId),
                    CurrentStep = cStep,
                    Action = "Reject",
                    RequestCode = Guid.NewGuid().ToString(),
                    SecurityCode = "fjyc.wicresoft"
                };
                Wicresoft.SelfService.WFInterface.ActionResult actionResult = IApproveFlow.Update(param);
                if (string.IsNullOrEmpty(actionResult.ErrorMsg) || actionResult.ErrorMsg.Contains("Can't find the WorkflowApplication :"))
                {
                    serviceStep nextStep = (serviceStep)Enum.Parse(typeof(serviceStep), actionResult.Step, true);
                    model.stepID = (int)nextStep;
                    model.stauts = (int)(serviceStatus)Enum.Parse(typeof(serviceStatus), actionResult.Status, true);
                    bool result = helper.UpdateITServiceStatus(model.serviceRequestID.Trim().ToLower(), model.stauts, model.stepID);
                    ServiceHistory history = new ServiceHistory();
                    history.serviceRequestID = serviceRequestID;
                    history.approverID = System.Web.HttpContext.Current.User.Identity.Name;
                    UserInfo ui = helper.getUserInfo_By_AccountID(history.approverID);
                    if (ui != null) history.approverName = ui.userName;
                    history.action = "拒绝";
                    history.comments = desc;
                    bool result2 = helper.CreateServiceRecordHistory(history);
                    if (result && result2)
                    {
                        helper.commitTransaction();
                        helper.closeDBConnection();
                        return Json(new { status = 1 });
                    }
                    else
                    {
                        helper.rollbackTransaction();
                        helper.closeDBConnection();
                        this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                    }
                }
                else
                {
                    this.rollbackWF(model.flowInstanceId, actionResult.Step);
                }
                return Json(new { status = 0 });
            }
            catch
            {
                helper.rollbackTransaction();
                helper.closeDBConnection();
                this.rollbackWF(model.flowInstanceId, Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString());
                return Json(new { status = 0 });
            }
        }
        [AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public JsonResult isDirector(string serviceRequestID)
        {
            bool isDirector = this.getCurrRole(serviceRequestID);
            if (isDirector)
            {
                ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
                model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
                if (model.serviceType != null && model.serviceType.cp == 3)
                {
                    return Json(new { isDirector = 2 }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { isDirector = 1 }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json(new { isDirector = 0 }, JsonRequestBehavior.AllowGet);
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public JsonResult approveServiceRequest(string serviceRequestID, bool needDirector, string approveNote)
        {
            ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
            roleType role = this.getRoleType(model);
            serviceStatus status = (serviceStatus)model.stauts;
            serviceStep step = (serviceStep)model.stepID;
            model.actions = Common.getActions(role, status, step);
            if (model.actions.Contains(actionType.approve) == false) return Json(new { status = 0 });
            string cStep = string.Empty;
            if (model.stepID.HasValue) cStep = Enum.Parse(typeof(serviceStep), model.stepID.Value.ToString()).ToString();
            model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
            model.account = helper.getUserInfo_By_AccountID(model.accountID);
            bool nd = default(Boolean);
            bool remoteApproval = false;
            if (model.serviceType != null && model.account != null)
            {
                remoteApproval = this.needRemoteApproval(model.serviceType.cp, model.serviceRequestID, model.account.company, model.appName, needDirector, out nd);
            }
            else
            {
                nd = needDirector;
            }
            Wicresoft.SelfService.WFInterface.ActionParam param = new Wicresoft.SelfService.WFInterface.ActionParam
            {
                FlowInstanceId = new Guid(model.flowInstanceId),
                CurrentStep = cStep,
                Action = "Approve",
                RequestCode = Guid.NewGuid().ToString(),
                SecurityCode = "fjyc.wicresoft",
                NeedDirector = nd,
                NeedCrossCompany = remoteApproval
            };
            Wicresoft.SelfService.WFInterface.ActionResult actionResult = IApproveFlow.Update(param);
            if (string.IsNullOrEmpty(actionResult.ErrorMsg) || actionResult.ErrorMsg.Contains("Can't find the WorkflowApplication :"))
            {
                model.serviceType = helper.getServiceList_By_ID(model.serviceTypeID);
                serviceStep nextStep = (serviceStep)Enum.Parse(typeof(serviceStep), actionResult.Step, true);
                model.stepID = (int)nextStep;
                model.stauts = (int)(serviceStatus)Enum.Parse(typeof(serviceStatus), actionResult.Status, true);
                bool result = helper.UpdateITServiceStatus(model.serviceRequestID.Trim().ToLower(), model.stauts, model.stepID);
                ServiceHistory history = new ServiceHistory();
                history.serviceRequestID = serviceRequestID;
                history.approverID = System.Web.HttpContext.Current.User.Identity.Name;
                UserInfo ui = helper.getUserInfo_By_AccountID(history.approverID);
                if (ui != null) history.approverName = ui.userName;
                history.action = "同意";
                history.comments = approveNote;
                bool result2 = helper.CreateServiceRecordHistory(history);
                if (result && result2)
                {
                    string tempCom = model.companyIDs;
                    int tempStatus = model.stauts;
                    if (nextStep == serviceStep.remote_interface)
                    {
                        List<UserInfo> users = helper.getRemoteApproverInfo_By_ServiceRequestID(serviceRequestID.Trim().ToLower());
                        foreach (UserInfo user in users)
                        {
                            if (!string.IsNullOrEmpty(user.company))
                            {
                                model.companyIDs = string.Concat(model.companyIDs, ";", user.company);
                                break;
                            }
                        }
                    }
                    if (model.stauts == (int)serviceStatus.Waiting && model.stepID == (int)serviceStep.event_process && Convert.ToBoolean(model.serviceType.isEvent) == false)
                    {
                        model.stauts = (int)serviceStatus.Done;
                    }
                    if (tempCom != model.companyIDs || tempStatus != model.stauts) helper.UpdateITService(model);
                    if (model.stauts == (int)serviceStatus.Waiting && model.stepID == (int)serviceStep.event_process)
                    {
                        try
                        {
                            //生成事件代码...（可以考虑使用异步，以减少页面的阻塞时间）
                            ITSMAccidentDAL eventHandler = new ITSMAccidentDAL();
                            string incidentId = eventHandler.createAccident(model);
                            helper.UpdateServiceRecords(model.serviceRequestID, null, null, incidentId);
                        }
                        catch
                        {
                            helper.rollbackTransaction();
                            helper.closeDBConnection();
                            this.rollbackWF(model.flowInstanceId, actionResult.Step);
                            return Json(new { status = 0 });
                        }
                    }
                    helper.commitTransaction();
                    helper.closeDBConnection();

                    #region //创建通知短信
                    if (needDirector)
                    {
                        MsgHelper wsMsg = new MsgHelper();
                        UserAndRoleInfo GetAssigners = new UserAndRoleInfo();
                        if (model.account.company == "宁德市烟草专卖局")
                        {
                            var assigners = GetAssigners.GetUserRoleRelationshipByRoleID(2);   //model.stepID
                            string description = model.description;
                            if (description.Length > 20)
                                description = description.Substring(0, 20);
                            string dsc = "自服务单提醒:" + model.serviceRequestID + ",提交人：" + model.account.userName + ",摘要:" + description;

                            if (assigners.Count > 0)
                            {
                                foreach (var item in assigners)
                                {
                                    WS_Message wsmodel = new WS_Message()
                                    {
                                        cChr_LoginID = item.AccountID,
                                        cInt_Status = 0,
                                        //AssignedTo = item.AccountID,
                                        cChr_PhoneNumber = item.Phone,
                                        cChr_Message = dsc,
                                        cChr_Others3 = model.account.company,
                                        Submitter = model.account.accountID,
                                        Short_Description = dsc
                                    };
                                    //bool retmsg = wsMsg.Create(wsmodel);
                                    wsMsg.CreateMessage(wsmodel);
                                }
                            }
                        }
                    }
                    #endregion
                    return Json(new { status = 1 });
                }
                else
                {
                    helper.rollbackTransaction();
                    helper.closeDBConnection();
                    this.rollbackWF(model.flowInstanceId, actionResult.Step);
                }
            }
            else
            {
                this.rollbackWF(model.flowInstanceId, actionResult.Step);
            }
            return Json(new { status = 0 });
        }
        [AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public JsonResult getHistoryByserviceRequestID(string serviceRequestID)
        {
            try
            {
                ServiceDetail model = helper.getServiceRequest_By_ID(serviceRequestID.Trim().ToLower());
                roleType role = this.getRoleType(model);
                serviceStatus status = (serviceStatus)model.stauts;
                serviceStep step = (serviceStep)model.stepID;
                model.actions = Common.getActions(role, status, step);
                if (model.actions.Contains(actionType.checkSuggestion) == false && model.actions.Contains(actionType.addSuggestion) == false) return Json(new { status = 0 });
                int suggestionStuts = 1;
                if (model.actions.Contains(actionType.addSuggestion)) suggestionStuts = 2;
                List<ServiceHistory> histories = helper.getServiceRecordHistory_By_serviceRequestID(serviceRequestID.Trim().ToLower());

                return Json(new { status = suggestionStuts, data = histories }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { status = 0 });
            }
        }
        #endregion
        #region upload and delete attachments
        public ContentResult Upload(HttpPostedFileBase fileData, string folder, string tempRequestID, string tempID)
        {
            string result = null;
            if (fileData != null)
            {
                try
                {
                    folder = string.Concat(folder, "/", tempRequestID);
                    if (System.IO.File.Exists(Request.MapPath(string.Concat("~/", folder, "/", fileData.FileName)))) return Content("Exists");
                    string dir = Request.MapPath(string.Concat("~/", folder, "/"));
                    if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                    Attachment att = new Attachment();
                    att.fileName = fileData.FileName;
                    att.fileSize = Convert.ToString(fileData.ContentLength / 1024);
                    att.uploadDate = DateTime.Now;
                    att.serviceRequestID = tempRequestID;
                    att.committerID = System.Web.HttpContext.Current.User.Identity.Name;
                    if (string.IsNullOrEmpty(att.committerID)) att.committerID = tempID;
                    UserInfo ui = helper.getUserInfo_By_AccountID(att.committerID);
                    if (ui != null) att.committerUserName = ui.userName;
                    bool insertStatus = helper.CreateAttachment(att);
                    if (insertStatus)
                    {
                        fileData.SaveAs(Path.Combine(dir + fileData.FileName));
                        result = string.Concat("{\"status\":\"1\",", "\"fileName\":\"", att.fileName, "\",\"fileSize\":\"", att.fileSize, "\",\"uploadDate\":\"", att.uploadDate.ToShortDateString(), "\",\"uploadUser\":\"", att.committerID, "\",\"uploadUserName\":\"", att.committerUserName, "\",\"requestid\":\"", tempRequestID, "\"}");
                    }
                    else
                    {
                        result = "{\"status\":\"0\"}";
                    }
                }
                catch
                {
                    result = null;
                }
            }
            return Content(result);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public JsonResult delAttachment(string folder, string fileName)
        {
            if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(fileName))
            {
                string aa = System.Web.HttpContext.Current.User.Identity.Name;
                string bb = string.Concat(aa, "--", System.Web.HttpContext.Current.User.Identity.Name);
                string fileFullPath = Request.MapPath(string.Concat("~/ITService/UploadFiles/", folder, "/", fileName));
                if (System.IO.File.Exists(fileFullPath)) System.IO.File.Delete(fileFullPath);
                bool deleteStatus = helper.delAttachment_By_ServiceRequestIDAndFileName(folder.ToLower().Trim(), fileName.Trim());
                if (deleteStatus)
                {
                    return Json(new { status = 1 });
                }
                else
                {
                    return Json(new { status = 0 });
                }
            }
            return Json(new { status = 0 });
        }

        public ActionResult downAttachment(string folder, string fileName)
        {
            if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(fileName))
            {
                string aa = System.Web.HttpContext.Current.User.Identity.Name;
                string bb = string.Concat(aa, "--", System.Web.HttpContext.Current.User.Identity.Name);
                string fileFullPath = Request.MapPath(string.Concat("~/ITService/UploadFiles/", folder, "/", fileName));
                string contenttype = FileContentTypeHelper.getFileContentType(fileName);
                if (System.IO.File.Exists(fileFullPath))
                {
                    return File(fileFullPath, contenttype, HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                }
            }
            return null;
        }
        #endregion
        #region data for drop down list
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult getlvl1()
        {
            List<BreakDownList> bdList = IBreakDown.GetTopCategory();
            return Json(bdList, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult getlvl2(string id, string categoryText, string company)
        {
            List<BreakDownList> bdList = new List<BreakDownList>();
            if (categoryText.Trim() == appSystemName)
            {
                bdList.Add(new BreakDownList { ID = 0, LvlName = "请选择..." });
                if (!string.IsNullOrEmpty(company))
                {
                    List<BusinessSystem> appsys = myAppSystem.getAppSystem(company.Trim());
                    foreach (BusinessSystem sys in appsys)
                    {
                        bdList.Add(new BreakDownList { ID = sys.ID, LvlName = sys.Name });
                    }
                }
            }
            else
            {
                int Id = Convert.ToInt32(id);
                bdList = IBreakDown.GetChildCategory(Id);
            }
            return Json(bdList, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult getlvl3(string id, string categoryText)
        {
            List<BreakDownList> bdList;
            if (categoryText.Trim() == appSystemName)
            {
                BreakDownList appSys = this.IBreakDown.GetTopCategory_By_Name(appSystemName).FirstOrDefault();
                if (appSys != null)
                {
                    bdList = this.IBreakDown.GetChildCategory(appSys.ID);
                }
                else
                {
                    bdList = new List<BreakDownList>();
                    bdList.Add(new BreakDownList { ID = 0, LvlName = "请选择..." });
                }
            }
            else
            {
                int Id = Convert.ToInt32(id);
                bdList = this.IBreakDown.GetChildCategory(Id);
            }
            return Json(bdList, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult getAppSystem(string category, string company)
        {
            List<BusinessSystem> bsList = this.myAppSystem.getAppSystem_By_AppCategory(category, company);
            return Json(bsList, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult getAppCategory(string company)
        {
            List<BusinessSystem> bsList = this.myAppSystem.getAppSystem(company);
            List<BusinessSystem> bsListResult = new List<BusinessSystem>();
            List<string> bsListTemp = new List<string>();
            foreach (BusinessSystem bs in bsList)
            {
                if (!bsListTemp.Contains(bs.category))
                {
                    bsListTemp.Add(bs.category);
                    bsListResult.Add(bs);
                }
            }
            bsListTemp = null;
            return Json(bsListResult, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region private methods
        private bool getCurrRole(string serviceRequestID)
        {
            string roleStr = System.Configuration.ConfigurationManager.AppSettings["directorRoleName"];
            if (string.IsNullOrEmpty(roleStr)) roleStr = "local_director;remote_director";
            string[] directorRoleName = roleStr.Split(';');
            return helper.getDirectorInfo_By_AccountID_And_DirectorRoles(serviceRequestID.Trim().ToLower(), System.Web.HttpContext.Current.User.Identity.Name, directorRoleName);
        }
        private bool needRemoteApproval(int remoteCode, string serviceRequestID, string company, string appSystem, bool needDirector, out bool nd)
        {
            bool needRemoteApproval = false;
            bool isDerector = this.getCurrRole(serviceRequestID);
            nd = needDirector;
            if (isDerector) nd = false;
            switch (remoteCode)
            {
                case 1:
                    needRemoteApproval = true;
                    break;
                case 2:
                    BusinessSystem businessSystem = this.myAppSystem.getAppSystem_By_AppName(appSystem, company);
                    if (businessSystem != null && businessSystem.isUnified == 1)
                    {
                        needRemoteApproval = true;
                    }
                    break;
                case 3:
                    if (isDerector)
                    {
                        needRemoteApproval = needDirector;
                    }
                    break;
                case 0:
                default:
                    break;
            }

            return needRemoteApproval;
        }
        private void rollbackWF(string flowInstanceId, string stepName)
        {
            Wicresoft.SelfService.WFInterface.RollBackParam param = new Wicresoft.SelfService.WFInterface.RollBackParam
            {
                FlowInstanceId = new Guid(flowInstanceId),
                CurrentStep = stepName,
                RequestCode = Guid.NewGuid().ToString(),
                SecurityCode = "fjyc.wicresoft"
            };
            IApproveFlow.RollBack(param);
        }
        private void generateSelectListDataModel(ServiceDetail model)
        {
            /*行政区隐藏
            if (model.account != null)
            {
                if (!string.IsNullOrEmpty(model.account.company))
                {
                    List<string> administriviteList = helper.getAdministrativeByCompany(model.account.company);
                    ViewData["selectListAdministrative"] = new SelectList(administriviteList, model.AdministrativeRegion);
                }
            }*/
            string key = model.serviceType.partialName.Trim().ToLower();
            string keyWords = ConfigurationManager.AppSettings[key];
            if (!string.IsNullOrEmpty(keyWords))
            {
                string[] strs = keyWords.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strs)
                {
                    switch (str)
                    {
                        case "serviceType":
                            List<ServiceList> serviceList = helper.getServiceLists_By_PartialName(key);
                            ViewData["selectList"] = new SelectList(serviceList, "serviceTypeID", "serviceName", model.serviceTypeID);
                            break;
                        case "OS":
                            List<string> osList = helper.getOSFromDB();
                            ViewData["selectListOS"] = new SelectList(osList, model.os);
                            break;
                        case "appType":
                            if (string.IsNullOrEmpty(model.appName))
                            {
                                List<BusinessSystem> allappSystemList = myAppSystem.getAppSystem(model.account.company);
                                Dictionary<string, string> categoryList = new Dictionary<string, string>();
                                foreach (BusinessSystem bs in allappSystemList)
                                {
                                    if (!categoryList.Keys.Contains(bs.category)) categoryList.Add(bs.category, bs.category);
                                }
                                ViewData["selectListCategory"] = new SelectList(categoryList, "key", "value");
                                if (categoryList.Count > 0)
                                {
                                    List<BusinessSystem> appSystemList = myAppSystem.getAppSystem_By_AppCategory(categoryList.Keys.First(), model.account.company);
                                    ViewData["selectListAppSystem"] = new SelectList(appSystemList, "Name", "Name");
                                }
                                else
                                {
                                    ViewData["selectListAppSystem"] = new SelectList(categoryList, "key", "value");
                                }
                            }
                            else
                            {
                                BusinessSystem appSystem = myAppSystem.getAppSystem_By_AppName(model.appName, model.account.company);
                                Dictionary<string, string> app = new Dictionary<string, string>();
                                app.Add(appSystem.Name, appSystem.Name);
                                Dictionary<string, string> category = new Dictionary<string, string>();
                                category.Add(appSystem.category, appSystem.category);
                                ViewData["selectListCategory"] = new SelectList(category, "key", "value");
                                ViewData["selectListAppSystem"] = new SelectList(app, "key", "value");
                            }
                            break;
                        case "Lvl1":
                            if (string.IsNullOrEmpty(model.breakDownlvl1))
                            {
                                List<BreakDownList> bdLvl1List = IBreakDown.GetTopCategory();
                                ViewData["selectListLvl1"] = new SelectList(bdLvl1List, "ID", "LvlName");
                                if (bdLvl1List.Count > 0)
                                {
                                    List<BreakDownList> bdLvl2List = IBreakDown.GetChildCategory(bdLvl1List[0].ID);
                                    ViewData["selectListLvl2"] = new SelectList(bdLvl2List, "ID", "LvlName");

                                    if (bdLvl2List.Count > 0)
                                    {
                                        List<BreakDownList> bdLvl3List = IBreakDown.GetChildCategory(bdLvl2List[0].ID);
                                        ViewData["selectListLvl3"] = new SelectList(bdLvl3List, "ID", "LvlName");
                                    }
                                }
                            }
                            else
                            {
                                List<BreakDownList> bdLvl1List = IBreakDown.GetTopCategory_By_Name(model.breakDownlvl1);
                                ViewData["selectListLvl1"] = new SelectList(bdLvl1List, "ID", "LvlName");

                                if (bdLvl1List.Count > 0)
                                {
                                    if (bdLvl1List[0].LvlName.Trim() == appSystemName)
                                    {
                                        List<BreakDownList> bdLvl2List = new List<BreakDownList>();
                                        if (model.account != null && !string.IsNullOrEmpty(model.account.company))
                                        {
                                            BusinessSystem app = myAppSystem.getAppSystem_By_AppName(model.breakDownlvl2, model.account.company.Trim());
                                            if (app != null)
                                            {
                                                bdLvl2List.Add(new BreakDownList { ID = app.ID, LvlName = app.Name });
                                            }
                                        }
                                        if (bdLvl2List.Count == 0) bdLvl2List.Add(new BreakDownList { ID = 0, LvlName = "请选择..." });
                                        ViewData["selectListLvl2"] = new SelectList(bdLvl2List, "ID", "LvlName");
                                        if (bdLvl2List.Count > 0)
                                        {
                                            List<BreakDownList> bdLvl3List = IBreakDown.GetChildCategory_By_Name(bdLvl1List[0].ID, model.breakDownlvl3);
                                            ViewData["selectListLvl3"] = new SelectList(bdLvl3List, "ID", "LvlName");
                                        }
                                    }
                                    else
                                    {
                                        List<BreakDownList> bdLvl2List = IBreakDown.GetChildCategory_By_Name(bdLvl1List[0].ID, model.breakDownlvl2);
                                        ViewData["selectListLvl2"] = new SelectList(bdLvl2List, "ID", "LvlName");

                                        if (bdLvl2List.Count > 0)
                                        {
                                            List<BreakDownList> bdLvl3List = IBreakDown.GetChildCategory_By_Name(bdLvl2List[0].ID, model.breakDownlvl3);
                                            ViewData["selectListLvl3"] = new SelectList(bdLvl3List, "ID", "LvlName");
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        private roleType getRoleType(ServiceDetail model)
        {
            roleType role = roleType.others;
            UserInfo ui_submitter = this.userSync.getUserInfo(model.accountID);

            string[] companyIDs = model.companyIDs.Split(';');
            string currCompany = companyIDs[companyIDs.Length - 1];
            List<UserInfo> currentApprover = helper.getCurrentApproverInfo_By_ServiceRequestID(model.serviceRequestID.Trim().ToLower(), currCompany.ToLower());
            bool isCurr = false;

            if (System.Web.HttpContext.Current.User.Identity.Name == ui_submitter.accountID)
            {
                if (!string.IsNullOrEmpty(model.companyIDs))
                {
                    foreach (UserInfo u in currentApprover)
                    {
                        if (u.accountID == System.Web.HttpContext.Current.User.Identity.Name)
                        {
                            role = roleType.ownerandapprover;
                            isCurr = true;
                            break;
                        }
                    }
                }
                else
                {
                    role = roleType.owner;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(model.companyIDs))
                {
                    foreach (UserInfo u in currentApprover)
                    {
                        if (u.accountID == System.Web.HttpContext.Current.User.Identity.Name)
                        {
                            role = roleType.approver;
                            isCurr = true;
                            break;
                        }
                    }
                    if (!isCurr)
                    {
                        int stepis = default(int);
                        if (model.stepID.HasValue) stepis = model.stepID.Value;
                        List<UserInfo> allApprover = helper.getAllApproverInfo(stepis, companyIDs);
                        foreach (UserInfo u in allApprover)
                        {
                            if (u.accountID == System.Web.HttpContext.Current.User.Identity.Name)
                            {
                                role = roleType.others;
                                break;
                            }
                        }
                    }
                }
            }

            return role;
        }
        #endregion
        #region Index pages without any dynamic data
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
        [Authorize]
        public ActionResult DeskTopIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult VPNIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult NetworkAccessIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult AntiVirusIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult AppSystemIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult InternalIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult BreakDownIndex()
        {
            return View();
        }
        [Authorize]
        public ActionResult BusinessIndex()
        {
            return View();
        }
        [Authorize]

        #endregion
        #region RolesConfiguration


        [Authorize]
        public ActionResult ConfigurationIndex()
        {
            int pageSize = 10;
            int pageIndex = 1;
            int counts;
            List<RolesConfig> cmodel = new List<RolesConfig>();
            string curAccountID = System.Web.HttpContext.Current.User.Identity.Name;
            UserInfo curUser = userSync.getUserInfo(curAccountID);

            int companyId = 0;
            foreach (object e in Enum.GetValues(typeof(Wicresoft.SelfService.DAO.CompanyCollection)))
            {
                if (Enum.GetName(typeof(Wicresoft.SelfService.DAO.CompanyCollection), e) == curUser.company)
                {
                    companyId = (int)e;
                }
                if (curUser.company == "福建省烟草专卖局")
                {
                    companyId = 0;
                }

            }

            List<RolesConfig> model = helper.getUserRolesConfigBy(string.Empty, string.Empty, null, 2, pageSize, pageIndex, out counts, companyId);

            if (curUser.company != "福建省烟草专卖局")
            {
                foreach (var item in model)
                {
                    if (item.company == curUser.company)
                        cmodel.Add(item);
                }
                // counts = cmodel.Count();
            }
            else
            {
                cmodel = model;
                //counts = cmodel.Count();
            }


            ViewData["size"] = pageSize;
            ViewData["index"] = pageIndex;
            ViewData["count"] = counts;
            return View(cmodel);
        }


        [Authorize]
        public JsonResult getConfigInfoBy(string accountID, string userName, int isAdmin, int roleID, int ps, int pi, int company)
        {
            int counts;
            List<RolesConfig> model = helper.getUserRolesConfigBy(accountID, userName, roleID, isAdmin, ps, pi, out counts, company);

            List<RolesConfig> cmodel = new List<RolesConfig>();
            string curAccountID = System.Web.HttpContext.Current.User.Identity.Name;
            UserInfo curUser = userSync.getUserInfo(curAccountID);
            if (curUser.company != "福建省烟草专卖局")
            {
                foreach (var item in model)
                {
                    if (item.company == curUser.company)
                        cmodel.Add(item);
                }
                //counts = cmodel.Count();
            }
            else
            {
                cmodel = model;
                //counts = cmodel.Count();
            }

            JsonResult json = new JsonResult
            {
                Data = new
                {
                    //list = model,
                    list = cmodel,
                    count = counts,
                }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult getSingleConfigInfoByAccountID(string accountID)
        {
            RolesConfig model = helper.getSingleRoleConfigByAccountID(accountID);

            string curAccountID = System.Web.HttpContext.Current.User.Identity.Name;
            UserInfo curUser = userSync.getUserInfo(curAccountID);
            if (curUser.company != "福建省烟草专卖局")
            {
                if (model.company != curUser.company)
                {
                    model = null;
                }
            }

            JsonResult json = new JsonResult
            {
                Data = new
                {
                    single = model
                }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult updateRoleInfoBy(string accountID, bool isAdmin, int roleID)
        {
            string curAccountID = System.Web.HttpContext.Current.User.Identity.Name;
            JsonResult json = null;
            if (curAccountID != accountID)
            {
                int c = helper.updateRoleInfoBy(accountID, isAdmin, roleID);
                json = new JsonResult
                {
                    Data = new
                    {
                        rowAffected = c
                    }
                };
            }
            else
            {
                json = new JsonResult
                {
                    Data = new
                    {
                        rowAffected = -1
                    }
                };
            }
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult insertRoleInfoBy(string accountID, bool isAdmin, int roleID)
        {
            int c = helper.insertRoleInfoBy(accountID, isAdmin, roleID);
            JsonResult json = new JsonResult
            {
                Data = new
                {
                    rowAffected = c
                }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }




        #endregion
        public string createCodeNumber()
        {
            return helper.getServiceRecordNo();
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (this.helper != null)
                helper.Dispose();
            if (IBreakDown != null && IBreakDown is Wicresoft.SelfService.BL.BreakDown)
            {
                ((Wicresoft.SelfService.BL.BreakDown)IBreakDown).Dispose();
            }

            if (userSync != null && userSync is UserSync)
            {
                ((UserSync)userSync).Dispose();
            }
        }
    }
}
